package com.uatair.common.mqtt.uploader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.uatair.common.mqtt.domain.DroneResponse;
import com.uatair.common.mqtt.domain.dto.ApiUploadResponse;
import com.uatair.common.mqtt.domain.task.*;
import com.uatair.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

@Slf4j
public class ZhiBaoYunTaskUploader {

    private static final String AG_Uav_url = "ag.uatair.com";
    private static final String AGRO_Uav_url = "agro.uatair.com";
    private static String AGUAVTOKEN;
    private static String AGROUAVTOKEN;

    public TaskDetail getTaskDetail(String taskId, Integer type) {
        String responseData = getGet("taskInfo", "taskId", taskId, type);
//        log.info("获取任务：{}，返回：{}", taskId, responseData);
        // 使用Gson解析JSON
        if (responseData==null)
            return null;
        Gson gson = new Gson();
        Type responseType = new TypeToken<ApiResponse<TaskDetail>>() {}.getType();
        ApiResponse<TaskDetail> taskResponse = gson.fromJson(responseData, responseType);
        if (taskResponse.code == 200) {
            TaskDetail taskDetail = taskResponse.data;
            return taskDetail;
        }
        return null;
    }

    public DroneResponse getDrone(String sn, Integer type) {
        String responseData = getGet("droneData", "sn", sn, type);
        // 使用Gson解析JSON
        Gson gson = new Gson();
        Type responseType = new TypeToken<ApiResponse<DroneResponse>>() {}.getType();
        ApiResponse<DroneResponse> droneResponse = gson.fromJson(responseData, responseType);
        if (droneResponse.code == 200) {
            DroneResponse droneOSD = droneResponse.data;
//            log.info("飞机osd数据：{}", droneOSD.toString());
            return droneOSD;
        }
        return null;
    }

    public List<Region> getRegionData(String taskId, Integer type) {
        String responseData = getGet("regions", "taskId", taskId, type);
        log.info("获取任务：{}，返回：{}", taskId, responseData);
        // 使用Gson解析JSON
        if (responseData==null)
            return null;
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        try {
            rootNode = mapper.readTree(responseData);
            // 提取 rows 数组并转换为 List<Region>
            JsonNode rowsNode = rootNode.get("rows");
            List<Region> regions = mapper.readValue( rowsNode.toString(), new TypeReference<List<Region>>() {});
            return regions;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static RecodeTask getRecode(ApiUploadResponse apiUploadResponse, JSONObject requestBody, String requestType){
        RecodeTask recode = new RecodeTask();
        recode.setUrl(apiUploadResponse.getUrl()); // 动态设置接口 URL
        recode.setRequestData(requestBody.toString());
        recode.setSerialNumber(apiUploadResponse.getSerialNumber()); // 设置流水号
        recode.setResponseData(apiUploadResponse.getResponseData()); // 设置返回数据
        recode.setCode(apiUploadResponse.getSuccessFlag());
        recode.setRequestType(requestType);
        recode.setRequestTime(new Date()); // 设置请求时间
        return recode;
    }

    public static void setTaskId(TaskDTO taskDTO, List<RecodeTask> recodeTaskList, RecodeTask recodeTask) {
        if (recodeTask!=null) {
            recodeTask.setPlatformId(taskDTO.getPlatformId());
            recodeTask.setTaskId(taskDTO.getTaskId());
            recodeTaskList.add(recodeTask);
        }
    }

    public String getGet(String urlName, String param, String paramValue, Integer type) {
        if (StringUtils.isEmpty(type==1?AGUAVTOKEN:AGROUAVTOKEN)) {
            try {
                getToken(type);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        // 1. 创建OkHttpClient实例（建议使用单例）
        OkHttpClient client =
                new OkHttpClient.Builder()
                        .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
                        .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
                        .build();

        // 2. 构建请求URL（带sn参数）
        HttpUrl url = new HttpUrl.Builder()
                .scheme("https")
                .host(type==1?AG_Uav_url:AGRO_Uav_url) // 替换为实际主机地址
                .addPathSegment("nyy") // 替换为实际路径
                .addPathSegment("oauth2")
                .addPathSegment(urlName)
                .addQueryParameter(param, paramValue)
                .addQueryParameter("pageNum", "1")
                .addQueryParameter("pageSize", "100")
                .build();

        // 3. 创建请求
        Request request = new Request.Builder()
                .url(url)
                .get() // 使用GET方法
                .addHeader("Authorization", "Bearer " + (type==1?AGUAVTOKEN:AGROUAVTOKEN))
                .build();

        // 4. 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("请求失败，状态码: {}", response.code());
            }
            // 5. 获取并解析响应数据
            String responseData = response.body().string();
            JSONObject responseJson = new JSONObject(responseData);
            if (!"200".equals(responseJson.get("code").toString()))
                getToken(type);
            return responseData;
        } catch (IOException e) {
            log.error("异常抛出： {}", String.valueOf(e));
            e.printStackTrace();
        }
        return null;
    }

    public void getToken(Integer type) throws IOException {
        // 1. 构建 FormBody（x-www-form-urlencoded 格式）
        RequestBody formBody = new FormBody.Builder()
                .add("client_id", "LFY")
                .add("client_secret", "k_54tdJWT.q2")
                .add("grant_type", "client_credentials")
                .build();
        // 2. 创建 OkHttp 请求
        String url = "https://"+(type==1?AG_Uav_url:AGRO_Uav_url)+"/nyy/oauth2/client_token";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody) // 使用 FormBody
                .addHeader("Content-Type", "application/x-www-form-urlencoded") // 明确指定 Content-Type
                .build();
        // 3. 发送请求并解析响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: HTTP " + response.code() + " - " + response.message());
            }
            String responseBody = response.body().string();
            JSONObject jsonObject = new JSONObject(responseBody);
            if (jsonObject.has("client_token")) {
                String clientToken = jsonObject.getString("client_token");
                log.info("更新联飞token： {}", responseBody);
                if (type==1)
                    AGUAVTOKEN = clientToken;
                else
                    AGROUAVTOKEN = clientToken;
            } else {
                throw new IOException("响应中没有 client_token，完整响应: " + responseBody);
            }
        }
    }
}
